package elements {
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;

	public class Car extends Sprite {
		private var speed:Number = 0, xSpeed:Number = 0, ySpeed:Number = 0, maxSpeed:Number, 
					accelerationRate:Number = 0.4, deaccelerationRate:Number = 0.96, reverseSpeed:Number = 1, 
					rotationAmount:int = 10, brakeSpeed:Number = 0.6;
		
		public function Car(bitData:BitmapData, maxSpeed:Number = 10) {
			//Set variables.
			this.maxSpeed = maxSpeed;
			
			//Create the car.
			var carBg:Bitmap = new Bitmap(bitData);
			
			//Add car to screen, centering it.
			carBg.x = -(carBg.width / 2);
			carBg.y = -(carBg.height / 2);
			this.addChild(carBg);
		}
		
		public function accelerate():void {
			//Accelerate the car if possible.
			if(speed < maxSpeed) speed += accelerationRate;
		}
		
		public function deaccelerate():void {
			//Deaccelerate the car.
			speed *= (Math.round(speed) < 1) ? 0 : deaccelerationRate;
		}
		
		public function brake():void {
			//Brake the car.
			speed *= brakeSpeed;
		}
		
		public function turn(dir:int):void {
			//Check which direction.
			if(! dir && speed > 0.3) {
				//Turn left.
				this.rotation -= rotationAmount * (speed / maxSpeed);
			} else if(dir && speed > 0.3) {
				//Turn right.
				this.rotation += rotationAmount * (speed / maxSpeed);
			}
		}
		
		public function speedo():String {
			//Return the speed.
			return (speed >= 10) ? '200' : Math.round(this.speed * 20).toString();
		}
		
		public function speedoAngle():Number {
			//Return the angle.
			return speed * 27;
		}
		
		public function update():void {
			//Calculate x and y speeds.
			xSpeed = Math.sin(this.rotation * (Math.PI/180)) * speed;
			ySpeed = Math.cos(this.rotation * (Math.PI/180)) * speed * -1;
			
			//Add speeds to update.
			this.x += xSpeed;
			this.y += ySpeed;
		}
		
	}
}